package com.supermarket.api.service.impl;

import com.supermarket.api.bean.product.ProductDetail;
import com.supermarket.api.common.Constants;
import com.supermarket.api.common.PageParam;
import com.supermarket.api.entity.ProductAttributeEntity;
import com.supermarket.api.entity.ProductEntity;
import com.supermarket.api.entity.ProductSkuEntity;
import com.supermarket.api.repository.ProductAttributeRepository;
import com.supermarket.api.repository.ProductRepository;
import com.supermarket.api.repository.ProductSkuRepository;
import com.supermarket.api.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 商品服务层
 * @author 李其伟
 * @date 2023/10/19
 */
@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private ProductAttributeRepository productAttributeRepository;

    @Autowired
    private ProductSkuRepository productSkuRepository;

    @Override
    public Page<ProductEntity> list(PageParam pageParam) {
        /**
         * 排序方式
         * 一定要是实体类的属性，而不能是数据库的字段
         */
        Sort sort = Sort.by(Sort.Direction.DESC, "sale");
        /**
         * 当前页， 每页记录数， 排序方式
         */
        Pageable pageable = PageRequest.of(pageParam.getPageNum() , pageParam.getPageSize(), sort);
        return productRepository.findAllByPublishStatus(Constants.PUBLISH_STATUS_UP,pageable);
    }

    @Override
    public ProductDetail detail(String sku) {
        ProductEntity entity = productRepository.findAllBySku(sku);
        List<ProductAttributeEntity> attributeList = productAttributeRepository.findAllBySkuOrderBySortAsc(sku);
        List<ProductSkuEntity> skuList = productSkuRepository.findAllBySkuOrderBySkuCodeAsc(sku);
        ProductDetail pd = new ProductDetail();
        pd.setProductEntity(entity);
        pd.setAttributeList(attributeList);
        pd.setSkuList(skuList);
        return pd;
    }

}
